package cn.qingyun.gis.modules.init.utils;

import cn.hutool.core.date.DatePattern;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.StringBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.io.Serializable;
import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @Description: 发送邮件通知工具类
 * @Author: wu-bin
 * @Date: 2021-06-30
 * @Version: V1.0
 */
@Slf4j
public class EmailSender {

    /***
     *发送邮件通知
     * @param email 受信邮箱地址
     * @param content 邮件内容
     * @param subject 邮件标题
     * @param type 有无附件（"attachment","html"或者"null"）
     * @param fileData 附件文件
     * @return 返回邮件服务接口信息（0失败，1成功）
     * @throws IOException
     */
    public static String sendMultiEmail(String email, String content, String subject, String type, MultipartFile fileData) throws IOException {
        HttpPost httpPost = new HttpPost("http://training.cicd.vpclub.cn/moses/notify/web/app/notify/sendMultiEmailCode");
        MultipartEntityBuilder builder = MultipartEntityBuilder.create().setMode(HttpMultipartMode.RFC6532);//解决附件名称中文乱码
        //builder.addTextBody("type", "attachment");
        //fileData = new File("D://我是附件文件.txt");
        ContentType contentType = ContentType.create("text/plain", StandardCharsets.UTF_8);
        builder.setContentType(ContentType.parse("multipart/form-data;boundary=<calculated when request is sent>"));
        if (type != null && !type.isEmpty()) {
            if (type.equals("attachment") && fileData != null) {
                builder.addPart("type", new StringBody(type, contentType));
                builder.addBinaryBody("fileData", fileData.getInputStream(), ContentType.MULTIPART_FORM_DATA, fileData.getOriginalFilename());// 文件流
            }
        }
        builder.addPart("toEmail", new StringBody(email, contentType));
        builder.addPart("content", new StringBody(content, contentType));
        builder.addPart("subject", new StringBody(subject, contentType));
        HttpEntity multipart = builder.build();
        return HttpRequestUtil.postSet(multipart, httpPost);
    }

//    public static boolean sendMime(Request request) throws IOException {
//        return sendMime(request, EmailSendJob.class);
//    }
//
//    public static boolean sendMime(Request request, Class<? extends Job> clazz) throws IOException {
//        if (Objects.nonNull(request.getSentDate())) {
//            long delay = request.getSentDate().getTime() - DateUtil.date().getTime();
//            if (delay > 0) {
//                QuartzTool.Client client = QuartzTool.Builder.build(
//                        new QuartzTool.JobEntity(clazz.getSimpleName(),
//                                IdWorker.getIdStr(),
//                                clazz,
//                                new JobDataMap(new HashMap<String, Request>() {{
//                                    put("entity", request);
//                                }})));
//
//                client.fixedDelay(delay / 1000);
//                return true;
//            }
//        }
//
//        // 如果没有定时，或者时间小于当前时间，直接发送
//        HttpRequest httpRequest = HttpUtil.createPost("http://training.cicd.vpclub.cn/moses/notify/web/app/notify/intact/send")
//                .form(request.toMap());
//        if (StrUtil.isNotBlank(request.getFileName()) && Objects.nonNull(request.getFile())) {
//            httpRequest.form("file", request.getFile());
//        }
//        HttpResponse httpResponse = httpRequest.execute();
//
//        return httpResponse.isOk();
//    }

    /***
     *发送邮件通知
     * @param email 受信邮箱地址
     * @param content 邮件内容
     * @param subject 邮件标题
     * @return 返回邮件服务接口信息（0失败，1成功）
     * @throws IOException
     */
    public static boolean sendCommonEmail(String email, String content, String subject) throws IOException {
        JSONObject params = new JSONObject();
        params.put("toEmail", email);
        params.put("content", content);
        params.put("subject", subject);
        params.put("type", "html");


        HttpRequest httpRequest = HttpUtil.createPost("http://training.cicd.vpclub.cn/moses/notify/web/app/notify/sendCommonEmailCode")
                .timeout(1000)
                .header("Content-Type", ContentType.APPLICATION_JSON.toString())
                .body(params.toJSONString());

        HttpResponse httpResponse = httpRequest.execute();
        return httpResponse.isOk();
    }

    @Data
    public static class Request implements Serializable {
        private static final long serialVersionUID = -6315233160648199431L;

        private Boolean html;
        private String[] to;
        private String[] cc;
        private String[] bcc;
        @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = DatePattern.UTC_MS_PATTERN, timezone = "GTM+8")
        private Date sentDate;
        private String subject;
        private String text;

        private File file;
        private String fileName;

        public Map<String, Object> toMap() {
            return new HashMap<String, Object>() {{
                put("html", html);
                put("to", to);
                put("cc", cc);
                put("bcc", bcc);
                put("sentDate", sentDate);
                put("subject", subject);
                put("text", text);
                put("fileName", fileName);
            }};
        }
    }
}
